import { login as apiLogin, getinfo as apiGetInfo } from '~/api/manager'
import { setToken, removeToken } from '~/composables/auth'

export const useAppStore = defineStore('app', () => {
    // 用户信息
    const user = ref({})
    // 侧边宽度
    const asideWidth = ref('250px')
    const menus = ref([])
    const ruleNames = ref([])

    function login({ username, password }) {
        return new Promise((resolve, reject) => {
            apiLogin(username, password)
                .then((res) => {
                    setToken(res.token)

                    resolve(res)
                })
                .catch((err) => reject(err))
        })
    }

    function getinfo() {
        return new Promise((resolve, reject) => {
            apiGetInfo()
                .then((res) => {
                    user.value = res
                    menus.value = res.menus
                    ruleNames.value = res.ruleNames

                    resolve(res)
                })
                .catch((err) => reject(err))
        })
    }

    function logout() {
        // 移除cookie里的token
        removeToken()
        // 清除当前用户状态
        user.value = {}
    }

    function handleAsideWidth() {
        asideWidth.value = asideWidth.value == '250px' ? '64px' : '250px'
    }

    return { user, asideWidth, menus, ruleNames, login, getinfo, logout, handleAsideWidth }
})
